import { Table, Card, Button, Popconfirm, Image, message } from 'antd';
import { getBannerApi, delBannerApi } from '@/api/banner';
import { useEffect, useState } from 'react';

// const dataSource = [
//   {
//     key: '1',
//     name: '胡彦斌',
//     age: 32,
//     address: '西湖区湖底公园1号',
//   },
//   {
//     key: '2',
//     name: '胡彦祖',
//     age: 42,
//     address: '西湖区湖底公园1号',
//   },
// ];

const Index = () => {
  // 因为需要响应式，所以dataSource要写在组件里面
  const [dataSource, setDataSource] = useState([]);

  const columns = [
    {
      // 默认情况下，将对应的dataIndex的字符串显示在表格中
      title: '图片',
      dataIndex: 'img',
      width: 200,
      // render属性可以将拿到的内容做处理
      render(text: string) {
        // return <img src={text} alt="" style={{ width: 150 }} />;
        return <Image width={100} src={text} />;
      },
      // render(text: string) {
      //   return <span>{text}</span>;
      // },
    },
    {
      title: 'alt',
      dataIndex: 'alt',
    },
    {
      title: 'link',
      dataIndex: 'link',
    },
    {
      title: '操作',
      dataIndex: 'bannerid',
      // record表示整一行数据
      render(text: string, record: any) {
        return (
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={confirm(record.bannerid)}
            okText="Yes"
            cancelText="No"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        );
      },
    },
  ];

  useEffect(() => {
    (async () => {
      const res = await getBannerApi();
      // const result = res.data.map((item: any) => {
      //   return {
      //     ...item,
      //     key: item.bannerid,
      //   };
      // });
      res && setDataSource(res.data);
    })();
  }, []);

  const confirm = (id: string) => async () => {
    // console.log(record);
    const res = await delBannerApi({ bannerid: id });
    if (res) {
      message.success('删除成功');
      const res2 = await getBannerApi();
      res2 && setDataSource(res2.data);
    }
  };

  return (
    <Card>
      {/* dataSource表示数据源，columns表示列信息 */}
      <Table dataSource={dataSource} columns={columns} rowKey="bannerid" />
    </Card>
  );
};

export default Index;
